package com.ruicar.afs.cloud.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.admin.service.SysDictDataService;
import com.ruicar.afs.cloud.admin.service.SysDictService;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.admin.entity.SysDict;
import com.ruicar.afs.cloud.admin.entity.SysDictData;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * The type DictDataController.
 * <p>
 * Created on 2019-02-21
 *
 * @author Fzero
 */
@Slf4j
@RestController
@Api(tags = "字典数据管理接口")
@RequestMapping("/dictdata")
@AllArgsConstructor
public class DictDataController {

	/**
	 * The Sys dict service.
	 */
	private final SysDictService sysDictService;

	/**
	 * The Sys dict data service.
	 */
	private final SysDictDataService sysDictDataService;


	/**
	 * Get by condition response.
	 *
	 * @param dictData   the dict data
	 * @param pageNumber the page number
	 * @param pageSize   the page size
	 * @return the response
	 */
	@RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
	@ApiOperation(value = "多条件分页获取字典列表")
	public IResponse getByCondition(@ModelAttribute SysDictData dictData,
	                                @RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize) {
		return new IResponse().setData(sysDictDataService.page(new Page(pageNumber, pageSize)
				, Wrappers.<SysDictData>query().lambda().eq(StringUtils.isNotEmpty(dictData.getStatus()), SysDictData::getStatus, dictData.getStatus())
						.like(StringUtils.isNotEmpty(dictData.getTitle()), SysDictData::getTitle, dictData.getTitle())
						.eq(StringUtils.isNotEmpty(dictData.getDictId()), SysDictData::getDictId, dictData.getDictId())));
	}

	/**
	 * Get by type response.
	 *
	 * @param type the type
	 * @return the response
	 */
	@RequestMapping(value = "/getByType/{type}", method = RequestMethod.GET)
	@ApiOperation(value = "通过类型获取")
	public IResponse<Object> getByType(@PathVariable String type) {
		return new IResponse<Object>().setData(DicHelper.getDicMaps(type).getOrDefault(type,new ArrayList<>()));
	}

	@RequestMapping(value = "/getByTypes", method = RequestMethod.POST)
	@ApiOperation(value = "通过类型获取所有字典")
	public IResponse<Object> getByTypes(@RequestParam("types") String[] types){
		return IResponse.success(DicHelper.getDicMaps(Arrays.asList(types)));
	}

	@RequestMapping(value = "/listAll", method = RequestMethod.POST)
	@ApiOperation(value = "获取所有数据字典")
	public IResponse<Object> listAll(){
		return IResponse.success(DicHelper.getAll());
	}

	/**
	 * Add response.
	 *
	 * @param dictData the dict data
	 * @return the response
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ApiOperation(value = "添加")
	@Transactional
	@SysLog(value = "添加数据字典")
	@PreAuthorize("@pms.hasPermission('sys_dicdata_add')")
	public IResponse<Object> add(@RequestBody SysDictData dictData) {
		SysDict dict = sysDictService.getById(dictData.getDictId());
		if (dict == null) {
			return new IResponse<Object>().setCode(CommonConstants.FAIL).setMsg("字典类型id不存在");
		}
		if(sysDictDataService.count(Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictId,dictData.getDictId()).eq(SysDictData::getValue,dictData.getValue()))>0){
			return new IResponse<Object>().setCode(CommonConstants.FAIL).setMsg("字典值重复");
		}
		sysDictDataService.save(dictData);
		sysDictDataService.publishDicDataToSync();
		return new IResponse<Object>().setMsg("添加成功");
	}

	/**
	 * Edit response.
	 *
	 * @param dictData the dict data
	 * @return the response
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ApiOperation(value = "编辑")
	@Transactional
	@SysLog(value = "添加数据字典")
	@PreAuthorize("@pms.hasPermission('sys_dicdata_edit')")
	public IResponse<Object> edit(@RequestBody SysDictData dictData) {
		if(sysDictDataService.count(Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictId,dictData.getDictId()).eq(SysDictData::getValue,dictData.getValue()).ne(SysDictData::getId,dictData.getId()))>0){
			return new IResponse<Object>().setCode(CommonConstants.FAIL).setMsg("字典值重复");
		}
		sysDictDataService.updateById(dictData);
		sysDictDataService.publishDicDataToSync();
		return new IResponse<Object>().setMsg("编辑成功");
	}

	/**
	 * Del by ids response.
	 *
	 * @param ids the ids
	 * @return the response
	 */
	@RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
	@ApiOperation(value = "批量通过id删除")
	@Transactional
	@SysLog(value = "批量通过id删除")
	@PreAuthorize("@pms.hasPermission('sys_dicdata_delete')")
	public IResponse<Object> delByIds(@PathVariable String[] ids) {
		sysDictDataService.removeByIds(Arrays.asList(ids));
		sysDictDataService.publishDicDataToSync();
		return new IResponse<Object>().setMsg("批量通过id删除数据成功");
	}
}
